package algorithm_demo.demo_advanced;

/**
 * 数组累加和-->滑动窗口
 * arr[3,2,1,1,1,6,1,1,1,1,1,1]  sum=6
 * 数组中返回子数组长度等于sum最长子数组的长度
 * 上述数组[3,2,1]长度为6，[6]长度为1，[1,1,1,1,1,1,1]长度为6,
 * 则等于sum的最长子数组的长度为6
 *
 * @author Api
 * @date 2023/4/2 23:55
 */
public class Code15_LongestSumSubArrayLengthInPositiveArray {
    // for test
    public static int right(int[] arr, int K) {
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j < arr.length; j++) {
                if (valid(arr, i, j, K)) {
                    max = Math.max(max, j - i + 1);
                }
            }
        }
        return max;
    }

    // for test
    public static boolean valid(int[] arr, int L, int R, int K) {
        int sum = 0;
        for (int i = L; i <= R; i++) {
            sum += arr[i];
        }
        return sum == K;
    }

    // for test
    public static int[] generatePositiveArray(int size, int value) {
        int[] ans = new int[size];
        for (int i = 0; i != size; i++) {
            ans[i] = (int) (Math.random() * value) + 1;
        }
        return ans;
    }

    // for test
    public static void printArray(int[] arr) {
        for (int i = 0; i != arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int len = 50;
        int value = 100;
        int testTime = 500000;
        System.out.println("test begin");
        for (int i = 0; i < testTime; i++) {
            int[] arr = generatePositiveArray(len, value);
            int K = (int) (Math.random() * value) + 1;
            int ans1 = getMaxLength(arr, K);
            int ans2 = right(arr, K);
            if (ans1 != ans2) {
                System.out.println("Oops!");
                printArray(arr);
                System.out.println("K : " + K);
                System.out.println(ans1);
                System.out.println(ans2);
                break;
            }
        }
        System.out.println("test end");
    }
    public static int getMaxLength(int[] arr, int K) {
        if (arr == null || arr.length == 0 || K <= 0) {
            return 0;
        }
        //窗口[L,R] [0,0]
        int L = 0;
        int R = 0;
        int windowsSum = arr[0];
        int len = 0;
        while (R < arr.length) {
            if (windowsSum == K){
                len = Math.max(len, R-L+1);
                windowsSum-=arr[L++];
            }else if (windowsSum < K){
                R++;
                if (R == arr.length){
                    break;
                }
                windowsSum+=arr[R];
            }else{
                windowsSum -= arr[L++];
            }
        }
        return len;
    }

}
